import os
import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QListWidget, QHBoxLayout, QLineEdit, \
    QPushButton, QMessageBox, QListWidgetItem, QCheckBox, QLabel

m_task_list_widget: QListWidget
m_task_name_line_edit: QLineEdit
m_win: QMainWindow

tasks = []


def save_tasks_data():
    with open("tasks.data", "w") as f:
        f.write(str(tasks))

def update_tasks_data():
    if not os.path.exists("tasks.data"):
        save_tasks_data()
    with open("tasks.data", "r") as f:
        global tasks
        content = f.read()
        try:
            tasks = eval(content)
        except Exception:
            save_tasks_data()



# 自定义控件类
class TaskItem(QWidget):
    def __init__(self, task_name, status=False):
        super().__init__()
        layout = QHBoxLayout()
        is_task_finish_check_box = QCheckBox()
        is_task_finish_check_box.setChecked(status)
        task_name_label = QLabel()
        task_name_label.setText(task_name)
        layout.addWidget(is_task_finish_check_box)
        layout.addWidget(task_name_label)
        self.setLayout(layout)

        is_task_finish_check_box.stateChanged.connect(self.check_box_state_changed)

    def check_box_state_changed(self, state):
        print(self.sender().isChecked())

        # 根据checkbox所在的位置，更新数据
        for i in range(m_task_list_widget.count()):
            if self.sender().parent() == m_task_list_widget.itemWidget(m_task_list_widget.item(i)):
                tasks[i]["status"] = self.sender().isChecked()

        save_tasks_data()



def click_add_task():
    task_name = m_task_name_line_edit.text()
    if task_name:
        item = QListWidgetItem()
        task_item = TaskItem(task_name)
        item.setSizeHint(task_item.sizeHint())
        m_task_list_widget.addItem(item)  # 先add 再set自定义控件
        m_task_list_widget.setItemWidget(item, task_item)

        tasks.append({"name": task_name, "status": False})

        save_tasks_data()

        m_task_name_line_edit.clear()
    else:
        QMessageBox.warning(m_win, "", "任务名称不能为空")

    print(tasks)


def main():
    app = QApplication(sys.argv)
    win = QMainWindow()
    global m_win
    m_win = win

    # 主控件 - 上（ListWidget）
    task_list_widget = QListWidget()
    global m_task_list_widget
    m_task_list_widget = task_list_widget

    update_tasks_data()

    for task in tasks:
        item = QListWidgetItem()
        task_item = TaskItem(task["name"], task["status"])
        item.setSizeHint(task_item.sizeHint())
        m_task_list_widget.addItem(item)  # 先add 再set自定义控件
        m_task_list_widget.setItemWidget(item, task_item)

    # 主控件 - 下（操作区域）- 输入框
    task_name_line_edit = QLineEdit()
    global m_task_name_line_edit
    m_task_name_line_edit = task_name_line_edit

    # 主控件 - 下（操作区域）- 添加按钮
    add_task_button = QPushButton("添加任务")
    add_task_button.clicked.connect(click_add_task)

    # 主控件 - 下（操作区域）
    tools_widget = QWidget()
    tools_layout = QHBoxLayout()
    tools_layout.addWidget(task_name_line_edit)
    tools_layout.addWidget(add_task_button)
    tools_widget.setLayout(tools_layout)

    # 主控件
    main_widget = QWidget()
    main_layout = QVBoxLayout()
    main_layout.addWidget(task_list_widget)
    main_layout.addWidget(tools_widget)
    main_widget.setLayout(main_layout)

    # 设置主控件
    win.setCentralWidget(main_widget)
    win.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
